package com.thinkinghead.mahjongrecorder;

import android.app.ActionBar;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import com.thinkinghead.mahjongrecorder.data.connect.ParseObjectConvertor;
import com.thinkinghead.mahjongrecorder.ui.dialog.DialogHelper;
import com.thinkinghead.mahjongrecorder.utils.TypeFaceManager;

public class AddReferenceRecordActivity extends BasicActivity {
	private static String TAG = "AddReferenceRecordActivity";
	Button btnSave;
	EditText txtRecordId;
	TextView tvRecordId;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_reference_record);
		initView();
		initFontFace();
		fnTitle();
	}

	private void fnTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("View Reference Record");
	}

	private void initView() {
		tvRecordId = (TextView) findViewById(R.id.tv_record_id);
		txtRecordId = (EditText) findViewById(R.id.txt_record_id);
		btnSave = (Button) findViewById(R.id.btn_save);
	}

	private void initFontFace() {
		Typeface tf = TypeFaceManager.getTypeFace(getAssets());
		if (tf != null) {
			tvRecordId.setTypeface(tf);
			txtRecordId.setTypeface(tf);
			btnSave.setTypeface(tf);
		}
	}

	public void fnSave(View v) {
		String recordId = txtRecordId.getText().toString();
		if (recordId.equalsIgnoreCase("")) {
			return;
		}
		fnCheckGameCodeExists(recordId);
	}

	private void fnCheckGameCodeExists(String oid) {
		final AddReferenceRecordActivity ctx = this;
		fnPreSave();
		ParseQuery<ParseObject> query = ParseQuery
				.getQuery(ParseObjectConvertor.TB_RECORD);

		// Retrieve the object by id
		query.getInBackground(oid, new GetCallback<ParseObject>() {
			public void done(ParseObject gRecord, ParseException e) {
				fnPostSave();
				if (e == null) {
					Log.d(TAG, "add ref");
					ParseUser user = ParseUser.getCurrentUser();
					ParseRelation<ParseObject> relation = user
							.getRelation("likes");
					relation.add(gRecord);
					user.saveInBackground();
					// finish();
				} else {
					DialogHelper.getOkAlertDialog(ctx,
							"Error in connecting server..", e.getMessage())
							.show();
				}
			}
		});
	}

	private void fnPreSave() {
		DialogHelper.fnShowDialog(this);
	}

	private void fnPostSave() {
		DialogHelper.fnCloseDialog();
	}
}
